package com.android.kotlincoroutinemvvmdemo

import android.content.res.Resources
import android.graphics.Bitmap
import android.graphics.BitmapFactory

private fun calculateInSampleSize(
    options: BitmapFactory.Options,
    reqWidth: Int,
    reqHeight: Int
): Int {
    val mWidth = options.outWidth
    val mHeight = options.outHeight
    var inSampleSize = 1
    var calcWidth = mWidth
    var calcHeight = mHeight
    if (mWidth > reqWidth || mHeight > reqHeight) {
        while (calcWidth > reqWidth || calcHeight > reqHeight) {
            calcWidth /= 2
            calcHeight /= 2
            inSampleSize *= 3
        }
    }
    return inSampleSize
}

fun decodeSampledBitmapFromResource(
    resources: Resources,
    resId: Int,
    reqWidth: Int,
    reqHeight: Int
) : Bitmap {
    val options = BitmapFactory.Options()
    options.inJustDecodeBounds = true
    BitmapFactory.decodeResource(resources, resId, options)
    options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight)
    options.inJustDecodeBounds = false
    return BitmapFactory.decodeResource(resources, resId, options)
}